package com.atguigu.daijia.customer.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import com.atguigu.daijia.customer.mapper.CustomerInfoMapper;
import com.atguigu.daijia.customer.mapper.CustomerLoginLogMapper;
import com.atguigu.daijia.customer.service.CustomerInfoService;
import com.atguigu.daijia.model.entity.customer.CustomerInfo;
import com.atguigu.daijia.model.entity.customer.CustomerLoginLog;
import com.atguigu.daijia.model.form.customer.UpdateWxPhoneForm;
import com.atguigu.daijia.model.vo.customer.CustomerLoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Slf4j
@Service
public class CustomerInfoServiceImpl extends ServiceImpl<CustomerInfoMapper, CustomerInfo> implements CustomerInfoService {

    @Autowired
    private WxMaService wxMaService;

    @Autowired
    private CustomerInfoMapper customerInfoMapper;

    @Autowired
    private CustomerLoginLogMapper customerLoginLogMapper;

    /*
    * 微信小程序登录
    * */
    @Override
    public Long login(String code) throws WxErrorException {
        //创建openid
        String openid = null;
        //通过code临时票据，和里面的appid和密钥，就可以从微信的服务器拿到WxMaJscode2SessionResult对象
        WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
        //通过sessionInfo拿到openid（每个微信用户的唯一标识）
        openid = sessionInfo.getOpenid();
        log.info("[小程序授权] openid = {}",openid);
        //通过openid查询这个用户是否第一次登录
        LambdaQueryWrapper<CustomerInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CustomerInfo::getWxOpenId,openid);
        CustomerInfo customerInfo = customerInfoMapper.selectOne(wrapper);

        if(customerInfo == null){
            //第一次登录，需要自动注册
            customerInfo = new CustomerInfo();
            customerInfo.setNickname(String.valueOf(System.currentTimeMillis()));
            customerInfo.setAvatarUrl("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
            customerInfo.setWxOpenId(openid);
            customerInfoMapper.insert(customerInfo);
        }

        //记录登录日志
        CustomerLoginLog customerLoginLog = new CustomerLoginLog();
        customerLoginLog.setCustomerId(customerInfo.getId());
        customerLoginLog.setMsg("小程序登录");
        customerLoginLogMapper.insert(customerLoginLog);

        return customerInfo.getId();
    }

    /*
    * 获取用户登录信息
    * */
    @Override
    public CustomerLoginVo getCustomerInfo(Long customerId) {
        //获取到这个对象
        CustomerInfo customerInfo = customerInfoMapper.selectById(customerId);
        //封装到CustomerLoginVo
        CustomerLoginVo customerLoginVo = new CustomerLoginVo();
        BeanUtils.copyProperties(customerInfo,customerLoginVo);//对象拷贝
        //用户是否需要绑定手机号
        String phone = customerInfo.getPhone();
        boolean hasText = StringUtils.hasText(phone);//phone == null -》 hasText == ture
        customerLoginVo.setIsBindPhone(hasText);
        return  customerLoginVo;
    }

    @Override
    public Boolean updateWxPhoneNumber(UpdateWxPhoneForm updateWxPhoneForm) throws WxErrorException {
        String code = updateWxPhoneForm.getCode();//临时票据
        Long customerId = updateWxPhoneForm.getCustomerId();//用户id
        //根据code获取到微信绑定号码
        WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(code);
        String phoneNumber = phoneNoInfo.getPhoneNumber();
        //更新用户信息
        CustomerInfo customerInfo = customerInfoMapper.selectById(customerId);
        customerInfo.setPhone(phoneNumber);
        customerInfoMapper.updateById(customerInfo);

        return true;
    }

    /*
     * 获取客户OpenId
     * */
    @Override
    public String getCutomerOpenId(Long customerId) {
        LambdaQueryWrapper<CustomerInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CustomerInfo::getId,customerId);
        CustomerInfo customerInfo = customerInfoMapper.selectOne(wrapper);
        return customerInfo.getWxOpenId();
    }


}
